<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var student = [
        {
          id: 1,
          parentId: 0,
          name: "王五",
        },
        {
          id: 2,
          parentId: 1,
          name: "小王",
        },
        {
          id: 3,
          parentId: 0,
          name: "张三",
        },
        {
          id: 4,
          parentId: 3,
          name: "小张",
        },
      ];

      var newStu = {};
      for (let i = 0; i < student.length; i++) {
        if (student[i].parentId === 0) {
          // 父
          newStu[student[i].id] = student[i];
        } else {
          // 子
          let key = student[i].parentId;
          newStu[key].children = newStu[key].children || [];
          newStu[key].children.push(student[i]);
        }
      }
      console.log(newStu);

      //   var arr = student.filter((item, index, arr) => {
      //     // console.log(item, index, arr);
      //     if (item.parentId === 0) {
      //       item.children = [];
      //       if (item.id === student[item.id].parentId) {
      //         item.children.push(student[item.id]);
      //       }
      //       return item.children;
      //     }
      //   });

      //   console.log(arr);
    </script>
  </body>
</html>
